package cn.tedu.baking.controller;

import io.minio.MinioClient;
import io.minio.ObjectWriteArgs;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
public class MinioUploadController {

    @Autowired
    private MinioClient minioClient;

    @RequestMapping(value="/minio/upload",method = RequestMethod.POST)
    public String doUpload(@RequestPart("picFile") MultipartFile picFile)
            throws Exception{//a.jpg
        //1.为文件重命名
        String originalFilename=picFile.getOriginalFilename();
        String newFileName= UUID.randomUUID()+
                originalFilename.substring(originalFilename.lastIndexOf("."));

        //2.上传文件
        ObjectWriteResponse res = minioClient.putObject(PutObjectArgs.builder()
                .bucket("public")
                .object(newFileName)
                .contentType(picFile.getContentType())
                .stream(picFile.getInputStream(), picFile.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build());
        // 返回可访问的图片链接
        return "http://192.168.237.129:9000/public/" + newFileName;
    }
}
